package ta.web.servlet;


import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import net.sf.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;


@WebServlet("/ckupload")
@MultipartConfig // 标识Servlet支持文件上传
public class CKupload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		// 存储路径
		String savePath = "d:/upload/";
		File baseFile = new File(savePath);
		if (!baseFile.exists()) {
			baseFile.mkdirs();
		}
		// 从请求参数中获取上传文件的类型：File/Image/Flash
		String type = request.getParameter("Type");
		if (type == null) {
			type = "File";
		}
		String date = DateTimeFormatter.ofPattern("yyyyMMdd").format(LocalDateTime.now());
		// 设定上传文件路径
		String currentPath = savePath + type + "/" + date + "/";
		File dirTest = new File(currentPath);
		if (!dirTest.exists()) {
			dirTest.mkdirs();
		}
		String path = "/upload/" + type + "/" + date + "/";
		// 获取上传的文件集合
		Collection<Part> parts = request.getParts();
		String fileName = "";
		for (Part part : parts) {
			if (part.getHeader("content-disposition").contains("filename")) {
				// 获取请求头，请求头的格式：form-data; name="file"; filename="snmp4j--api.zip"
				String header = part.getHeader("content-disposition");
				// 获取文件名
				fileName = getFileName(header);
				// 把文件写到指定路径
				String time = DateTimeFormatter.ofPattern("HHmmss").format(LocalDateTime.now());
				fileName = time + fileName;
				part.write(currentPath + fileName);
			}
		}
		PrintWriter out = response.getWriter();
		String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ fileName;

		JSONObject obj = new JSONObject();
		obj.put("uploaded", 1);
		obj.put("fileName", fileName);
		obj.put("url", url);
		out.write(obj.toString());
	}

	/**
	 * 根据请求头解析出文件名 请求头的格式：火狐和google浏览器下：form-data; name="file";
	 * filename="snmp4j--api.zip" IE浏览器下：form-data; name="file";
	 * filename="E:\snmp4j--api.zip"
	 * 
	 * @param header 请求头
	 * @return 文件名
	 */
	public String getFileName(String header) {
		String[] tempArr1 = header.split(";");
		String[] tempArr2 = tempArr1[2].split("=");
		// 获取文件名，兼容各种浏览器的写法
		String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
		return fileName;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
